import frappe
from erpnext.controllers.queries import supplier_query


@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def custom_supplier_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
    result = supplier_query(doctype, txt, searchfield, start, page_len, filters, as_dict)
    item_code = filters.get('item_code')
    if item_code:
        valid_suppliers = frappe.get_all('Item Supplier', filters={'parent': item_code}, pluck ='supplier')
        if valid_suppliers:
            if as_dict:
                result = [r for r in result if r.name in valid_suppliers]
            else:
                result = [r for r in result if r[0] in valid_suppliers]
    return result
